package com.barrygee.android.threesixtyapp;


import android.app.Activity;
import android.util.Log;
import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Environment;
import android.hardware.Camera;
import android.graphics.PixelFormat;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Locale;

import com.barrygee.android.threesixtyapp.data.satellite.DirectionalData;
import com.barrygee.android.threesixtyapp.data.satellite.LatitudeLongitudeData;



public class Main extends Activity 
{
	private SurfaceView preview = null;
    private SurfaceHolder previewHolder = null;
    private Camera camera = null;
    private Handler theHandler = new Handler();
    
    private String latitude;
    private String longitude;
    private String direction;
    private String timeDate;
    private SimpleDateFormat sdfDate;
    private SimpleDateFormat sdfTime;
    
    public LatitudeLongitudeData latitudeLongitude;
	public DirectionalData directionData;
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        init();
    }
    
    
    @Override
    public void onPause()
    {
    	// remove objects from memory
    	latitudeLongitude = null;
    	
    	super.onPause();
    }

    
    @Override
    public void onResume() 
    {
    	latitudeLongitude = new LatitudeLongitudeData();
    	
    	camera = Camera.open();
    	camera.setDisplayOrientation(90);
    	
    	super.onResume();
    }    
    
    
    
    
    // perform setup's
    private void init()
    {
    	latitudeLongitude = new LatitudeLongitudeData();
    	
    	directionData = new DirectionalData();
    	
        setUpCameraPreview();
        
        setLatitude();
        
        setLongitude();
        
        setDirection();
    }
    
    
    
    
    private void setUpCameraPreview()
    {
        preview = (SurfaceView)findViewById(R.id.cameraPreview);
        previewHolder = preview.getHolder();
        previewHolder.addCallback(surfaceCallback);
        previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
    
    
    
    
    private Runnable takePicture = new Runnable()
    {
    	public void run() 
    	{
    		theHandler.postDelayed(takePicture, 5000); 

    						// (Camera.ShutterCallback shutter, Camera.PictureCallback raw, Camera.PictureCallback postview, Camera.PictureCallback jpeg)
    		camera.takePicture(null, null, cameraCallback);

    	}
    	
    };
    
    
    
    
    // time / date
    public String timeDate()
    {
    	sdfDate = new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
    	sdfTime = new SimpleDateFormat("HH-mm-ss", Locale.UK);
    	
		timeDate =  sdfDate.format(new Date(System.currentTimeMillis())) + "-" + sdfTime.format(new Date(System.currentTimeMillis()));
    	
		return timeDate;
    }
    
    
    
    
	// latitude
	public void setLatitude()
	{
		this.latitude = "lat" + latitudeLongitude.Latitude();
	}
	
	public String latitude()
	{
		return this.latitude;
	}
	
	
	
	
	// longitude
	public void setLongitude()
	{
		this.longitude = "long" + latitudeLongitude.Longitude();
	}
	
	public String longitude()
	{
		return this.longitude;
	}
	
	
	
	
	// direction
	public void setDirection()
	{
		this.direction = "dir-" + directionData.Direction();
	}
	
	public String direction()
	{
		return this.direction;
	}
	


	
	 private Camera.Size getOptimalPreviewSize(int width, int height, Camera.Parameters parameters) 
	 {
		Camera.Size result = null;
			
		for (Camera.Size size : parameters.getSupportedPreviewSizes()) 
		{
			if (size.width<=width && size.height<=height) 
			{
				if (result==null) 
				{
					result=size;
				}
				else 
				{
					int resultDelta=width-result.width+height-result.height;
					int newDelta=width-size.width+height-size.height;
						
					if (newDelta<resultDelta) 
					{
						result=size;
					}
				}
			}
		}
			
		return(result);
	}
	 
	
	
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() 
{
    public void surfaceCreated(SurfaceHolder holder) 
    {
    	try 
    	{
    		camera.setPreviewDisplay(previewHolder);

    		// Every 5 seconds
    		theHandler.postDelayed(takePicture, 5000);//Settings.REPEAT_IN_MILLISECONDS
    	}
    	catch(Throwable t) 
    	{
    		Log.e("surfacecallback Exception", "Exception in setPreviewDisplay()", t);
    	}
    }

    	
	
    	
    
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) 
	{
		Camera.Parameters parameters = camera.getParameters();
		
		Camera.Size size= getOptimalPreviewSize(width, height, parameters);

		if(size!=null) 
		{
			// set preview width / height
		    parameters.setPreviewSize(size.width, size.height);
		
			// set picture format
			parameters.setPictureFormat(PixelFormat.JPEG);
				
			// turn off camera flash
			parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
			
			// set focus to infinity
			parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_INFINITY);
			
			// set the camera parameters
			camera.setParameters(parameters);
				
			// start the camera preview
			camera.startPreview();
		}
	}

	
	 public void surfaceDestroyed(SurfaceHolder holder) 
	 {
	 	// stop the camera preview
		camera.stopPreview();
		
		// release the camera
		camera.release();
		
		// set the camera object ready for garbage collection
		camera = null;
	 }
	 
 };
 


Camera.PictureCallback cameraCallback = new Camera.PictureCallback() 
{
    public void onPictureTaken(byte[] data, Camera Camera) 
    {
    	new SavePhoto().execute(data);
    	camera.startPreview();
    }
};


    
    
// inner class to handle the saving of images to the device  
class SavePhoto extends AsyncTask<byte[], String, String> 
{
	 @Override
     protected String doInBackground(byte[]... jpeg) 
	 { 																				
		 File photo = new File(Environment.getExternalStorageDirectory(), "360App-" + timeDate() + latitude() + longitude() + direction() + ".jpg");
		 Log.v("FILE_NAME", "360App-" + timeDate() + latitude() + longitude() + direction() + ".jpg");
		 try 
		 {
			 FileOutputStream fos = new FileOutputStream(photo.getPath());
			 fos.write(jpeg[0]);
			 fos.close();
		 }
		 catch (java.io.IOException e) 
		 {
			 Log.e("360App", "Exception in photoCallback", e);
		 }

		 return(null);
    	
     	 }
     }
}
